<template>
	<view class="good-detail">
		<!-- 添加骨架屏组件 -->
		<uv-skeletons :loading="loading" :skeleton="skeleton">
			<!-- 原有内容作为插槽 -->
			<view>
				<!-- 顶部按钮组 -->
				<view class="top-btns">
					<view class="btn back-btn" @tap="goBack">
						<uv-icon name="arrow-left" size="24" color="#333" bold></uv-icon>
					</view>
					<view class="btn contact-btn" @tap="contactService" v-if="good.servicePhone">
						<uv-icon name="server-fill" size="24" color="#333"></uv-icon>
					</view>
				</view>

				<!-- 商品主图轮播 -->
				<swiper class="swiper" circular indicator-dots autoplay>
					<swiper-item v-for="(img, index) in mainImages" :key="index">
						<image :src="img.imageUrl" mode="aspectFill"></image>
					</swiper-item>
				</swiper>

				<!-- 商品基本信息 -->
				<view class="info-section">
					<view class="price-box">
						<view class="price-info">
							<!-- 根据支付方式显示不同的价格信息 -->
							<template v-if="good.paymentType === 1">
								<text class="price">{{good.price}}</text>
							</template>
							<template v-else-if="good.paymentType === 2">
								<text class="points">{{good.points}}<text class="unit">积分</text></text>
							</template>
							<template v-else-if="good.paymentType === 3">
								<text class="mixed-price">
									<text class="points">{{good.pointsCashPoints}}</text>
									<text class="unit">积分</text>
									<text class="plus">+</text>
									<text class="cash">{{good.pointsCashPrice}}</text>
								</text>
							</template>
							<text class="shipping" :class="good.shippingFee ? 'paid' : 'free'">
								{{good.shippingFee ? `运费: ¥${good.shippingFee}` : '包邮'}}
							</text>
						</view>
						<view class="sales-info">
							<text class="sales">销量 {{good.sales}}</text>
							<text class="stock">库存 {{good.stock}}</text>
						</view>
					</view>
					<view class="title">{{good.name}}</view>
					<view class="desc">{{good.description}}</view>
					
					<!-- 礼品卡/券标识 -->
					<view class="gift-tag" v-if="good.paymentType === 4 || good.paymentType === 5">
						<uv-icon :name="good.paymentType === 4 ? 'gift' : 'coupon'" size="32" color="#FF5733"></uv-icon>
						<text>需要{{good.paymentType === 4 ? good.giftCardNum + '张礼品卡' : good.giftVoucherNum + '张礼品券'}}</text>
					</view>
				</view>

				<!-- 配送地址 -->
				<view class="address-section">
					<view class="address-content">
						<text class="label">配送</text>
						<view class="value-wrapper">
							<template v-if="isUserLoggedIn">
								<template v-if="address.id">
									<text class="address">
										{{address.province}}{{address.city}}{{address.district}}
									</text>
								</template>
								<text v-else class="no-address">请先添加收货地址</text>
							</template>
							<text v-else class="no-address">请先登录</text>
						</view>
					</view>
				</view>

				<!-- 支付方式 - 仅在非礼品卡/券时显示 -->
				<view class="payment-section" v-if="good.paymentType < 4">
					<view class="section-title">支付方式</view>
					<view class="payment-tag" :class="'payment-type-' + good.paymentType">
						<template v-if="good.paymentType === 1">
							<text class="amount">¥{{good.price}}</text>
							<text class="label">现金支付</text>
						</template>
						<template v-else-if="good.paymentType === 2">
							<text class="amount">{{good.points}}</text>
							<text class="label">积分兑换</text>
						</template>
						<template v-else-if="good.paymentType === 3">
							<view class="mixed-payment">
								<text class="points">{{good.pointsCashPoints}}积分</text>
								<text class="plus">+</text>
								<text class="cash">¥{{good.pointsCashPrice}}</text>
							</view>
							<text class="label">积分+现金</text>
						</template>
					</view>
				</view>

				<!-- 商家信息 -->
				<view class="merchant-section">
					<view class="merchant-header">
						<image class="merchant-avatar" :src="merchant.image" mode="aspectFill"></image>
						<view class="merchant-info">
							<text class="merchant-name">{{merchant.merchantName || merchant.name}}</text>
							<view class="merchant-detail">
								<text class="merchant-desc">{{merchant.des}}</text>
								<text class="merchant-address">{{merchant.province}}{{merchant.city}}{{merchant.district}}</text>
							</view>
						</view>
					</view>
				</view>

				<!-- 商品详情 -->
				<view class="detail-section" v-if="detailImages && detailImages.length > 0">
					<view class="section-title">商品详情</view>
					<view class="detail-images">
						<image v-for="(img, index) in detailImages" :key="index" :src="img.imageUrl" mode="widthFix"></image>
					</view>
				</view>

				<!-- 底部操作栏 -->
				<view class="action-bar">
					<view class="price-display">
						<!-- 根据支付方式显示不同的价格信息 -->
						<template v-if="good.paymentType === 1">
							<text class="price">{{good.price}}</text>
						</template>
						<template v-else-if="good.paymentType === 2">
							<text class="points">{{good.points}}<text class="unit">积分</text></text>
						</template>
						<template v-else-if="good.paymentType === 3">
							<text class="mixed-price">
								<text class="points">{{good.pointsCashPoints}}</text>
								<text class="unit">积分</text>
								<text class="plus">+</text>
								<text class="cash">{{good.pointsCashPrice}}</text>
							</text>
						</template>
						<template v-else>
							<text class="gift-price">
								{{good.paymentType === 4 ? good.giftCardNum + '张礼品卡' : good.giftVoucherNum + '张礼品券'}}
							</text>
						</template>
					</view>
					<view class="right-btns">
						<button class="buy-now" @tap="buyNow" 
							:disabled="good.status === 0 || good.stock <= 0">
							<uv-icon name="bag" size="32" color="#fff"></uv-icon>
							立即购买
						</button>
					</view>
				</view>
			</view>
		</uv-skeletons>
	</view>
</template>

<script>
	import { isUserLoggedIn, isMerchantLoggedIn } from '@/plugins/auth.js'

	export default {
		data() {
			return {
				loading: true, // 添加loading状态
				skeleton: [
					// 轮播图骨架
					{
						type: 'custom',
						style: 'width: 750rpx; height: 750rpx;'
					},
					// 价格区域骨架
					{
						type: 'flex',
						style: 'padding: 20rpx 30rpx;',
						children: [
							{
								type: 'custom',
								style: 'width: 200rpx; height: 60rpx;'
							},
							{
								type: 'custom',
								style: 'width: 120rpx; height: 40rpx; margin-left: auto;'
							}
						]
					},
					// 标题和描述骨架
					{
						type: 'line',
						style: 'margin: 20rpx 30rpx; height: 40rpx;'
					},
					{
						type: 'line',
						style: 'margin: 20rpx 30rpx; height: 32rpx; width: 80%;'
					},
					// 地址区域骨架
					{
						type: 'flex',
						style: 'margin: 30rpx; padding: 20rpx; background: #f8f8f8;',
						children: [
							{
								type: 'line',
								style: 'width: 100rpx; height: 40rpx;'
							},
							{
								type: 'line',
								style: 'width: 400rpx; height: 40rpx; margin-left: 20rpx;'
							}
						]
					},
					// 商家信息骨架
					{
						type: 'flex',
						style: 'margin: 30rpx; padding: 20rpx;',
						children: [
							{
								type: 'avatar',
								style: 'width: 100rpx; height: 100rpx;'
							},
							{
								type: 'line',
								num: 2,
								style: 'margin-left: 20rpx;',
								gap: '10rpx'
							}
						]
					}
				],
				good: {
					id: null,
					categoryId: null,
					name: '',
					price: 0,
					description: '',
					sales: 0,
					
					paymentType: 1,
					points: 0,
					pointsCashPoints: 0,
					pointsCashPrice: 0,
					stock: 0,
					servicePhone: '',
					status: 1,
					shippingFee: null,
					merchantId: null,
				},
				merchant: {
					id: null,
					name: '',
					merchantName: '',
					image: '',
					des: '',
					street: '',
					director: '',
					phone: '',
					openingHours: '',
					status: 1
				},
				mainImages: [], // 主图列表
				detailImages: [], // 详情图片列表
				address: {},
				isUserLoggedIn: false
			}
		},

		onLoad(options) {
			// 获取路由参数
			const {
				goodsId,
				categoryId
			} = options
			if (goodsId && categoryId) {
				this.fetchGoodsDetail(goodsId, categoryId)
			}
		},

		onShow() {
			// 每次页面显示时检查登录状态
			this.checkLoginStatus();
		},

		methods: {
			// 获取商品详情
			async fetchGoodsDetail(goodsId, categoryId) {
				try {
					const data = await this.$http.get(
						`/mall/goods/customer/byId?goodsId=${goodsId}&categoryId=${categoryId}`);

					if (data) {
						// 解构商品信息
						const {
							mainImages,
							detailImages,
							...goodInfo
						} = data;

						// 更新商品基本信息
						this.good = {
							...this.good,
							...goodInfo
						}

						// 更新图片列表
						this.mainImages = mainImages || []
						this.detailImages = detailImages || []
						
						// 如果有商家ID，获取商家信息
						if (this.good.merchantId) {
							await this.fetchMerchantInfo()
						}

						// 数据加载完成,关闭骨架屏
						this.loading = false;
					} else {
						uni.showToast({
							title: '获取商品信息失败',
							icon: 'none'
						})
					}
				} catch (e) {
					console.error('获取商品详情失败:', e)
					// 出错时也需要关闭骨架屏
					this.loading = false;
					uni.showToast({
						title: '网络异常，请稍后重试',
						icon: 'none'
					})
				}
			},

			// 获取商家信息
			async fetchMerchantInfo() {
				try {
					const data = await this.$http.get(`/merchant/byId?id=${this.good.merchantId}`);
					
					if (data) {
						this.merchant = {
							...this.merchant,
							...data
						}
					} else {
						console.error('获取商家信息失败')
					}
				} catch (e) {
					console.error('获取商家信息失败:', e)
				}
			},
			
			// 跳转到店铺
			goToShop() {
				if (this.merchant.id) {
					uni.navigateTo({
						url: `/subpkg/merchant_detail/merchant_detail?id=${this.merchant.id}`
					})
				}
			},
			
			// 联系客服
			contactService() {
				if (this.good.servicePhone) {
					uni.makePhoneCall({
						phoneNumber: this.good.servicePhone,
					})
				}
			},

			// 返回上一页
			goBack() {
				uni.navigateBack({
					delta: 1
				})
			},

			// 获取默认地址
			async fetchDefaultAddress() {
				try {
					const data = await this.$http.get('/address/default')
					if (data) {
						this.address = data
					}
				} catch (e) {
					console.error('获取默认地址失败:', e)
				}
			},
			
			// 添加检查登录状态的方法
			checkLoginStatus() {
				this.isUserLoggedIn = isUserLoggedIn();
				// 如果已登录则获取默认地址
				if (this.isUserLoggedIn) {
					this.fetchDefaultAddress();
				} else {
					// 如果未登录，清空地址信息
					this.address = {};
				}
			},
			
			// 修改立即购买方法
			buyNow() {
				// 重新检查登录状态
				this.checkLoginStatus();
				
				// 检查登录状态
				if (!this.isUserLoggedIn) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
					setTimeout(() => {
						uni.navigateTo({
							url: '/subpkg/login_page/login_page'
						});
					}, 1500);
					return;
				}
				
				// 检查是否是商家登录
				if (isMerchantLoggedIn() && !this.isUserLoggedIn) {
					uni.showToast({
						title: '请先登录用户端',
						icon: 'none'
					});
					return;
				}
				
				if (!this.good.id) {
					uni.showToast({
						title: '商品信息不完整',
						icon: 'none'
					});
					return;
				}
				
				uni.navigateTo({
					url: `/subpkg/create_order/create_order?goodsId=${this.good.id}&categoryId=${this.good.categoryId}&paymentType=${this.good.paymentType}&count=${1}`
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import 'mall_good_detail.scss';
</style>